const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 获取商品评价列表
router.get('/products/:id/reviews', async (req, res) => {
  try {
    const { id } = req.params;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;

    const [reviews] = await db.promise().query(`
      SELECT r.*, u.username
      FROM product_reviews r
      LEFT JOIN users u ON r.user_id = u.id
      WHERE r.product_id = ?
      ORDER BY r.created_at DESC
      LIMIT ? OFFSET ?
    `, [id, limit, offset]);

    res.json({
      success: true,
      data: reviews
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 发表评价
router.post('/products/:id/reviews', async (req, res) => {
  try {
    const { id } = req.params;
    const { content, rating } = req.body;
    const user_id = req.user.id;

    const [result] = await db.promise().query(
      'INSERT INTO product_reviews (product_id, user_id, content, rating) VALUES (?, ?, ?, ?)',
      [id, user_id, content, rating]
    );

    res.json({
      success: true,
      data: {
        id: result.insertId,
        product_id: id,
        user_id,
        content,
        rating
      },
      message: '评价发表成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

module.exports = router; 